package Controller;

import Dao.*;
import Entity.*;
import Utils.SimpleTools;
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

public class StaffController extends Application implements Initializable {
    Stage primaryStage = new Stage();
    Officer officer;

    @FXML
    private Label nameLabel;
    @FXML
    private AnchorPane settlePane;
    @FXML
    private TextField itspassword;
    @FXML
    private TextField itsusername;
    @FXML
    private TextField itsid;
    @FXML
    private TextField itsname;
    @FXML
    private TextField itsphone;
    /**————————————————————————————修改个人信息————————————————————————*/
    @FXML
    void settle(MouseEvent event) {
        settlePane.setVisible(true);
    }
    @FXML
    void Finish(ActionEvent event) throws IOException {
        Officer it = StaffDao.getInstance().getOfficer();
        Officer its = new Officer(it.getUsername(),it.getPassword(),it.getName(),
                it.getId(),it.getBirth(), it.getSpeciality(),it.getType(),
                it.getPhone(),it.getJurisdiction());

        if(!SimpleTools.isEmpty(itsname.getText())){
            its.setName(itsname.getText());
        }
        if(!SimpleTools.isEmpty(itsusername.getText())){
            if(SignupDao.iscontain(itsusername.getText())){
                SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "该用户名已注册");
                itsusername.clear();
            }
            else its.setUsername(itsusername.getText());
        }
        if(!SimpleTools.isEmpty(itspassword.getText())){
            its.setPassword(itspassword.getText());
        }
        if(!SimpleTools.isEmpty(itsid.getText())){
            if(itsid.getText().length()!=18){
                SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "警告", "请正确输入身份证号");
                itsid.clear();
            }
            else its.setId(itsid.getText());
        }
        if(!SimpleTools.isEmpty(itsphone.getText()))
            its.setPhone(itsphone.getText());
        settlePane.setVisible(false);

        nameLabel.setText("亲爱的"+ its.getName()+"，欢迎回家");

        AdministratorDao.replace(it,its);
    }


    @FXML
    private Button goback;
    @FXML
    private Button backButton;
    @FXML
    private AnchorPane patientpane;
    @FXML
    private AnchorPane questionPane;
    @FXML
    private AnchorPane bedPane;
    @FXML
    private AnchorPane patternPane;
    @FXML
    private AnchorPane buildingPane;
    @FXML
    private Button addButton;
    @FXML
    private AnchorPane userAddPane;
    @FXML
    private TextField patientName;
    @FXML
    private TextField patientBirth;
    @FXML
    private TextField patientSex;
    @FXML
    private TextField patientAge;
    @FXML
    private TextField patientPhone;
    @FXML
    private TextField patientUrgent;
    @FXML
    private TextField patientUrgencall;
    @FXML
    private TextField patientBed;
    @FXML
    private TableView<Patient> userTable;
    @FXML
    private TableColumn<Patient, String> usernametable;
    @FXML
    private TableColumn<Patient, String> userbirthtable;
    @FXML
    private TableColumn<Patient, String> usersextable;
    @FXML
    private TableColumn<Patient, String> useragetable;
    @FXML
    private TableColumn<Patient, String> userphonetable;
    @FXML
    private TableColumn<Patient, String> userconnecttable;
    @FXML
    private TableColumn<Patient, String> userurcalltable;
    @FXML
    private TableColumn<Patient, String> userbedtable;
    @FXML
    private TableColumn<Patient, String> userassesstable;
    @FXML
    private TextField Patientsearch;
    private final ObservableList<Patient> cellData = FXCollections.observableArrayList();

    public StaffController(){}


    @FXML
    void backButton(ActionEvent event) {
        userAddPane.setVisible(false);
        backButton.setVisible(false);
    }
    //床位实际上是房间
    /**——————————————————————————————————病患管理界面————————————————————————*/
    @FXML
    void patientButton(ActionEvent event) throws IOException {

        buildingPane.setVisible(false);
        patternPane.setVisible(false);
        questionPane.setVisible(false);
        bedPane.setVisible(false);
        patientpane.setVisible(true);

        userTable.setEditable(true);

        cellData.clear();
        cellData.addAll(StaffDao.getPatients());
        userTable.setItems(null);
        userTable.setItems(cellData);

    }

    @FXML//——————————————————————————————————————————————————添加界面
    void addButton(ActionEvent event) {
        userAddPane.setVisible(true);
        backButton.setVisible(true);
    }
    @FXML
    void fadd(ActionEvent event) throws IOException {
        String[] properties = {patientName.getText(),patientBirth.getText(),patientSex.getText(),
                patientAge.getText(), patientPhone.getText(),patientUrgent.getText(),
                patientUrgencall.getText(),patientBed.getText()};
        if(SimpleTools.isempty(properties)) SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "警告", "请输入全部信息");
        else{
//            Patient patient = new Patient(properties[0],properties[1],properties[2],properties[3])
            PatientDao.add(properties);
            patientName.clear();
            patientBirth.clear();
            patientSex.clear();
            patientAge.clear();
            patientPhone.clear();
            patientUrgent.clear();
            patientUrgencall.clear();
            patientBed.clear();


            cellData.remove(0,cellData.size());
            cellData.addAll(StaffDao.getPatients());
            userTable.setItems(null);
            userTable.setItems(cellData);
        }
    }

    @FXML//——————————————————————————————————————————————————保存
    void changeButton(ActionEvent event) throws IOException {
        StaffDao.StorePatients(userTable.getItems());
        SimpleTools.informationDialog(Alert.AlertType.INFORMATION, "提示", "", "保存成功！");


    }

    @FXML//模糊查找//——————————————————————————————————————————————————查询界面
    void searchButton(ActionEvent event) throws IOException {
        if(Patientsearch.getText()!=null){
            cellData.clear();
            cellData.addAll(PatientDao.search(Patientsearch.getText()));
        }
        userTable.setItems(null);
        userTable.setItems(cellData);

    }

    @FXML//删除界面
    void deleteButton(ActionEvent event) throws IOException {
        Patient patient = userTable.getSelectionModel().getSelectedItem();
        List<Patient> list = userTable.getItems();
        list.remove(patient);
        StaffDao.StorePatients(list);

        cellData.remove(0,cellData.size());
        cellData.addAll(StaffDao.getPatients());
        userTable.setItems(null);
        userTable.setItems(cellData);
    }



    @FXML
    private Label patientInformation;
    @FXML
    private ChoiceBox<String> chooseIntobed;
    @FXML
    private ListView<String> BedBuild;
    @FXML
    private ListView<String> BedFloor;
    @FXML
    private ListView<String> BedRoom;
    @FXML
    private ListView<String> BedPatient;

    /**————————————————————————————房间管理界面——————————————————————*/
    @FXML
    void bedButton(ActionEvent event) throws IOException {
        buildingPane.setVisible(false);
        patientpane.setVisible(false);
        questionPane.setVisible(false);
        bedPane.setVisible(true);
        patternPane.setVisible(false);
        if(StaffDao.getPatients()!=null){

            ObservableList<String> strList = FXCollections.observableArrayList(StaffDao.getRoomBuildings());
//            BedBuild.setItems(null);
            BedBuild.setItems(strList);
            ObservableList<String> patientList = FXCollections.observableArrayList(PatientDao.noRoomPatientNames());
            chooseIntobed.setItems(patientList);
        }

    }
    //List列表
    @FXML
    void BedBuild(MouseEvent event) throws IOException {
        if(BedBuild.getSelectionModel().getSelectedItem()!=null){
            String buildname = BedBuild.getSelectionModel().getSelectedItem();
            List<Room> rooms = StaffDao.searchRooms(buildname,null,null);
            List<String> roomfloor = new ArrayList<>();
            for(Room room:rooms){
                String floor = room.getFloorlocation();
                if(!roomfloor.contains(floor)) roomfloor.add(floor);
            }
            ObservableList<String> strList = FXCollections.observableArrayList(roomfloor);
            BedFloor.setItems(strList);
            BedPatient.setItems(null);
            BedRoom.setItems(null);
        }
    }
    @FXML
    void BedFloor(MouseEvent event) throws IOException {
        String floorname = BedFloor.getSelectionModel().getSelectedItem();
        List<Room> rooms = StaffDao.searchRooms(BedBuild.getSelectionModel().getSelectedItem(),floorname,null);
        List<String> roomlist = new ArrayList<>();
        for(Room room:rooms){
            String name = room.getName();
            if(!roomlist.contains(name)) roomlist.add(name);
        }
        ObservableList<String> strList = FXCollections.observableArrayList(roomlist);
        BedRoom.setItems(strList);
        BedPatient.setItems(null);
    }
    @FXML
    void BedRoom(MouseEvent event) throws IOException {
        List<Room> room = StaffDao.searchRooms(BedBuild.getSelectionModel().getSelectedItem(),BedFloor.getSelectionModel().getSelectedItem(),BedRoom.getSelectionModel().getSelectedItem());
        List<Patient> list = PatientDao.byRoom(room.get(0));
        List<String> patientnames = new ArrayList<>();
        for (Patient patient:list){
            String name = patient.getName();
            if(!patientnames.contains(name)) patientnames.add(name);
        }
        ObservableList<String> strList = FXCollections.observableArrayList(patientnames);
        BedPatient.setItems(null);
        BedPatient.setItems(strList);
    }
    @FXML
    void BedPatient(MouseEvent event) throws IOException {
        List<Room> room = StaffDao.searchRooms(BedBuild.getSelectionModel().getSelectedItem(),BedFloor.getSelectionModel().getSelectedItem(),BedRoom.getSelectionModel().getSelectedItem());
        String name = BedPatient.getSelectionModel().getSelectedItem();
        List<Patient> list = PatientDao.byRooms(room);
        Patient patient = new Patient();
        for(Patient patientd:list){
            if(patientd.getName().equals(name)) patient = patientd;
        }
        patientInformation.setText(patient.toString());
        patientInformation.setVisible(true);
    }

    @FXML
    void intobed(ActionEvent event) throws IOException {
        if(BedRoom.getSelectionModel().getSelectedItem()!=null){
            if(chooseIntobed.getSelectionModel().getSelectedItem()!=null){
                //处理房间
                List<Room> allrooms = StaffDao.getRooms();
                List<Room> rooms = StaffDao.searchRooms(BedBuild.getSelectionModel().getSelectedItem(),BedFloor.getSelectionModel().getSelectedItem(),BedRoom.getSelectionModel().getSelectedItem());
                Room room = rooms.get(0);

                List<Boolean> fulls = room.getFull();
                Room r1 = new Room(room.getBuildinglocation(),room.getFloorlocation(),room.getName(),room.isCommon(),room.getBeds(),fulls);

                for(int i=0;i<fulls.size();i++){
                    if(!fulls.get(i)){
                        fulls.set(i,true);
                        break;
                    }
                }
                room.setFull(fulls);
                for(Room r:allrooms){
                    if(r.toString().equals(room.toString())) allrooms.set(allrooms.indexOf(r),room);
                }
                StaffDao.changeRoom(r1,room);

                //处理病患
                String name = chooseIntobed.getSelectionModel().getSelectedItem();
                List<Patient> list = StaffDao.getPatients();
                for(Patient p:list){
                    if(p.getName().equals(name)){
                        p.setRoom(room.toString());
                        break;
                    }
                }
                StaffDao.StorePatients(list);


                //刷新
                ObservableList<String> patientList = FXCollections.observableArrayList(PatientDao.noRoomPatientNames());
                chooseIntobed.setItems(patientList);
                //该房间内的病人集合
                List<Patient> patientlist = PatientDao.byRoom(room);
                List<String> patientnames = new ArrayList<>();
                for (Patient patient:patientlist){
                    String sname = patient.getName();
                    if(!patientnames.contains(sname)) patientnames.add(sname);
                }
                ObservableList<String> strList = FXCollections.observableArrayList(patientnames);
//                BedPatient.setItems(null);
                BedPatient.setItems(strList);
            }
            else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "错误", "请选择入住的患者！");
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "错误", "请选择入住的房间！");

    }

    @FXML
    void outbed(ActionEvent event) throws IOException {
        if(BedPatient.getSelectionModel().getSelectedItem()!=null){
            //处理房间信息
            List<Room> allrooms = StaffDao.getRooms();
            List<Room> rooms = StaffDao.searchRooms(BedBuild.getSelectionModel().getSelectedItem(),BedFloor.getSelectionModel().getSelectedItem(),BedRoom.getSelectionModel().getSelectedItem());
            Room room = rooms.get(0);
            List<Boolean> fulls = room.getFull();

            for(int i=0;i<fulls.size();i++){
                if(!fulls.get(i)){
                    fulls.set(i,false);
                    break;
                }
            }
            room.setFull(fulls);
            for(Room r:allrooms){
                if(r.toString().equals(room.toString())) allrooms.set(allrooms.indexOf(r),room);
            }
            StaffDao.storeRooms(allrooms);

            //处理病患信息
            List<Patient> list = StaffDao.getPatients();
            for(Patient p:list){
                if(p.getName().equals(BedPatient.getSelectionModel().getSelectedItem())&&p.getRoom().equals(room.toString())){
                    p.setRoom(null);
                    break;
                }
            }
            StaffDao.StorePatients(list);

            ObservableList<String> patientlist = FXCollections.observableArrayList(PatientDao.noRoomPatientNames());
            chooseIntobed.setItems(patientlist);
            //刷新列表
            List<Patient> patientList = PatientDao.byRoom(room);
            List<String> patientnames = new ArrayList<>();
            for (Patient patient:patientList){
                String name = patient.getName();
                if(!patientnames.contains(name)) patientnames.add(name);
            }
            ObservableList<String> strList = FXCollections.observableArrayList(patientnames);
//            BedPatient.setItems(null);
            BedPatient.setItems(strList);
        }
       else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "错误", "请选择退院的患者！");
    }



    @FXML
    private TextField questiontext;
    @FXML
    private TextField optionOne;
    @FXML
    private TextField optionTwo;
    @FXML
    private TextField optionThree;
    @FXML
    private CheckBox option1;
    @FXML
    private CheckBox option3;
    @FXML
    private CheckBox option2;
    @FXML
    private TextField typequestion;
    @FXML
    private TableView<Question> QuestionTable;
    @FXML
    private TableColumn<Question, String> numColumn;
    @FXML
    private TableColumn<Question, Character> typeColumn;
    @FXML
    private TableColumn<Question, String> questionColumn;
    @FXML
    private ListView<String> OptionList;
    @FXML
    private TextField NewTextField;
    @FXML
    private TextField questionSearch;

    private final ObservableList<Question> cellData2 = FXCollections.observableArrayList();
    /**————————————————————————————————————————问题管理——————————————————————*/
    @FXML
    void questionButton(ActionEvent event) throws IOException {
        cellData2.clear();
        cellData2.addAll(QuestionDao.getQuestions());

        questionPane.setVisible(true);
        buildingPane.setVisible(false);
        patientpane.setVisible(false);
        bedPane.setVisible(false);
        patternPane.setVisible(false);
        QuestionTable.setItems(null);
        QuestionTable.setItems(cellData2);

    }
    @FXML
    void questionSearch(MouseEvent event) throws IOException {
        cellData2.clear();
        cellData2.addAll(QuestionDao.searchQuestions(questionSearch.getText()));
        QuestionTable.setItems(null);
        QuestionTable.setItems(cellData2);
    }

    @FXML
    void addquestion(ActionEvent event) throws IOException {
        String[] questions = {questiontext.getText(),optionOne.getText(),optionTwo.getText(),optionThree.getText(),typequestion.getText()};
        String[] options = {optionOne.getText(),optionTwo.getText(),optionThree.getText()};
        boolean[] booleans ={option1.isSelected(),option2.isSelected(),option3.isSelected()};
        if(SimpleTools.isempty(questions)) SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "警告", "请输入全部信息");
        else {
            Question question = new Question(questions[0],questions[4].charAt(0),options,booleans);
            QuestionDao.storeQuestion(question);

            cellData2.clear();
            cellData2.addAll(QuestionDao.getQuestions());
            QuestionTable.setItems(null);
            QuestionTable.setItems(cellData2);
        }
        questiontext.clear();
        optionThree.clear();
        optionTwo.clear();
        optionOne.clear();
        typequestion.clear();
        option3.setSelected(false);
        option2.setSelected(false);
        option1.setSelected(false);
    }
    @FXML
    void changeuquestion(ActionEvent event) throws IOException {
        String changstr1 = OptionList.getSelectionModel().getSelectedItem();
        Question question = QuestionTable.getSelectionModel().getSelectedItem();
        String changstr2 = question.getContent();
        List<Question> list = QuestionDao.getQuestions();
        List<String> strList = new ArrayList<>();
        if(changstr1!=null){
            for(Question q:list){
                if(q.getContent().equals(changstr2)) {
                    for(int i=0;i<q.getOptions().length;i++){
                        if(q.getOptions()[i].equals(changstr1)){
                            String[] options = q.getOptions();
                            options[i] = NewTextField.getText();
                            q.setOptions(options);
                        }
                        strList.add(q.getOptions()[i]);
                    }
                }
            }
            NewTextField.clear();
            QuestionDao.changAll(list);

            ObservableList<String> strlist = FXCollections.observableArrayList(strList);
            OptionList.setItems(null);
            OptionList.setItems(strlist);


        }
        else if(changstr2!=null){
            for(Question q:list){
                if(q.getContent().equals(changstr2)) q.setContent(NewTextField.getText());
            }
            QuestionDao.changAll(list);

            cellData2.clear();
            cellData2.addAll(QuestionDao.getQuestions());
            QuestionTable.setItems(null);
            QuestionTable.setItems(cellData2);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "错误", "请选择您想要修改的问题内容或选项");

        cellData2.clear();
        cellData2.addAll(QuestionDao.getQuestions());
        QuestionTable.setItems(null);
        QuestionTable.setItems(cellData2);
    }
    @FXML
    void chooseQuestion(MouseEvent event) throws IOException {
        if(QuestionTable.getSelectionModel().getSelectedItem().getOptions()!=null){
            ObservableList<String> strList = FXCollections.observableArrayList(QuestionTable.getSelectionModel().getSelectedItem().getOptions());
            OptionList.setItems(null);
            OptionList.setItems(strList);
        }
    }
    @FXML
    void deletequestion(ActionEvent event) throws IOException {
        Question question = QuestionTable.getSelectionModel().getSelectedItem();
        if(question!=null){
            if(SimpleTools.informationDialog(Alert.AlertType.CONFIRMATION, "提示", null, "您确定要删除该问题吗？")){
                QuestionDao.deleteQuestion(question);

                cellData2.clear();
                cellData2.addAll(QuestionDao.getQuestions());
                QuestionTable.setItems(null);
                QuestionTable.setItems(cellData2);
            }
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "请至少选择一个问题！");
    }



    @FXML
    private TableView<Pattern> patternTable;
    @FXML
    private TableColumn<Pattern, String> PatternnameColumn;
    @FXML
    private TableColumn<Pattern, Character> PatterntypeColumn;
    @FXML
    private AnchorPane changePatternPane;
    @FXML
    private TableView<Question> Patternquestiontable;
    @FXML
    private TableColumn<Question, String> Patternquestioncolumn;
    @FXML
    private AnchorPane addPatternPane;
    @FXML
    private TextField Patternname;
    @FXML
    private TextField Patterntype;
    @FXML
    private TextField changePatternname;
    @FXML
    private TableView<Question> addtoPatterntable;
    @FXML
    private TableColumn<Question, Character> addtoPatternnum;
    @FXML
    private TableColumn<Question, String> addtoPatternquestion;
    @FXML
    private Button addtoPatternButton;

    private final ObservableList<Pattern> cellData3 = FXCollections.observableArrayList();
    private final ObservableList<Question> cellData4 = FXCollections.observableArrayList();
    private final ObservableList<Question> cellData5 = FXCollections.observableArrayList();
    private final ObservableList<Question> cellData6 = FXCollections.observableArrayList();
    /**————————————————————————————————————————模板管理————————————————————*/

    @FXML
    void patternButton(ActionEvent event) throws IOException {
        cellData3.clear();
        cellData3.addAll(PatternDao.getPatterns());

        buildingPane.setVisible(false);
        patternPane.setVisible(true);
        questionPane.setVisible(false);
        bedPane.setVisible(false);
        patientpane.setVisible(false);

        patternTable.setItems(null);
        patternTable.setItems(cellData3);
    }

    @FXML
    void addPatternButton(ActionEvent event){
        addPatternPane.setVisible(true);

        addtoPatternnum.setCellValueFactory(cellData4 -> new SimpleObjectProperty(cellData4.getValue().getType()));
        addtoPatternquestion.setCellValueFactory(cellData4 -> new SimpleObjectProperty(cellData4.getValue().getContent()));

    }
    @FXML
    void deletePatternButton(ActionEvent event) throws IOException {
        Pattern pattern = patternTable.getSelectionModel().getSelectedItem();
        if(pattern!=null) {
            if(SimpleTools.informationDialog(Alert.AlertType.CONFIRMATION, "提示", null, "您确定要删除该模板吗？"))
                PatternDao.deletePattern(pattern);

            cellData3.clear();
            cellData3.addAll(PatternDao.getPatterns());
            patternTable.setItems(null);
            patternTable.setItems(cellData3);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "请至少选择一个模板！");
    }
    @FXML
    void changePatternButton(ActionEvent event) throws IOException {
        Pattern pattern = patternTable.getSelectionModel().getSelectedItem();
        if(pattern==null) SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "警告", "请选择您想要修改的模板");
        else{
            addtoPatterntable.setVisible(false);
            addtoPatternButton.setVisible(false);
            changePatternPane.setVisible(true);
            List<Question> questions = PatternDao.byName(pattern.getName());
            if(questions==null){
                Patternquestiontable.setItems(null);
            }
            else{
                Patternquestioncolumn.setCellValueFactory(cellData4 -> new SimpleObjectProperty(cellData4.getValue().getContent()));

                cellData4.clear();
                cellData4.addAll(questions);
                Patternquestiontable.setItems(null);
                Patternquestiontable.setItems(cellData4);

            }
        }
    }
    @FXML
    void StartAssessButton(ActionEvent event) throws Exception {
        Pattern pattern = patternTable.getSelectionModel().getSelectedItem();
        if(pattern!=null){
            PatternDao.StartAssess(pattern);
            (new AssessController()).showWindow();

            cellData.clear();
            cellData.addAll(StaffDao.getPatients());
            userTable.setItems(null);
            userTable.setItems(cellData);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "请选择评估模板！");
    }

    @FXML
    void FinishChangePatternButton(ActionEvent event) throws IOException {
        String name = changePatternname.getText();
        List<Pattern> list = PatternDao.getPatterns();
        if(name!=null){
            Pattern pattern = patternTable.getSelectionModel().getSelectedItem();
            for(Pattern p:list){
                if(p.equals(pattern)){
                    p.setName(name);
                    break;
                }
            }
            PatternDao.StorePatterns(list);
        }

        SimpleTools.informationDialog(Alert.AlertType.INFORMATION, "提示", "", "保存成功！");
        changePatternPane.setVisible(false);

        changePatternname.clear();
        cellData3.clear();
        cellData3.addAll(list);
        patternTable.setItems(null);
        patternTable.setItems(cellData3);
    }
    @FXML
    void FinishAddPatternButton(ActionEvent event) throws IOException {
        String[] properties = {Patternname.getText(),Patterntype.getText()};
        if(SimpleTools.isempty(properties)) SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "错误", "请输入全部信息！");
        else{
            Pattern pattern = new Pattern(properties[0],properties[1].charAt(0),null);
            PatternDao.AddPattern(pattern);
            Patterntype.clear();
            Patternname.clear();
            addPatternPane.setVisible(false);

            cellData3.clear();
            cellData3.addAll(PatternDao.getPatterns());
            patternTable.setItems(null);
            patternTable.setItems(cellData3);
        }
    }

    @FXML
    void RemovefrompatternButton(ActionEvent event) throws IOException {
        Question question = Patternquestiontable.getSelectionModel().getSelectedItem();
        if(question!=null) {
            if(SimpleTools.informationDialog(Alert.AlertType.CONFIRMATION, "提示", null, "您确定要从模板中删除该问题吗？"))
                PatternDao.deleteQuestion(patternTable.getSelectionModel().getSelectedItem(),question);

            cellData4.clear();
            cellData4.addAll(PatternDao.byName(patternTable.getSelectionModel().getSelectedItem().getName()));
            Patternquestiontable.setItems(null);
            Patternquestiontable.setItems(cellData4);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "请至少选择一个问题！");
    }
    @FXML
    void AddtopatternButton(ActionEvent event) throws Exception {
        addtoPatternButton.setVisible(true);
        addtoPatterntable.setVisible(true);

        try {
            cellData5.addAll(PatternDao.UnbyName(patternTable.getSelectionModel().getSelectedItem()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        addtoPatternnum.setCellValueFactory(cellData5 -> new SimpleObjectProperty(cellData5.getValue().getType()));
        addtoPatternquestion.setCellValueFactory(cellData5 -> new SimpleObjectProperty(cellData5.getValue().getContent()));

        cellData5.clear();
        cellData5.addAll(PatternDao.UnbyName(patternTable.getSelectionModel().getSelectedItem()));
        addtoPatterntable.setItems(null);
        addtoPatterntable.setItems(cellData5);
    }
    @FXML
    void FinishaddtoPatternButton(ActionEvent event) throws IOException {
        Question question = addtoPatterntable.getSelectionModel().getSelectedItem();
        if(question!=null){
            PatternDao.addtoPattern(patternTable.getSelectionModel().getSelectedItem(),question);
            addtoPatterntable.setVisible(false);
            addtoPatternButton.setVisible(false);

            List<Question> questionList = PatternDao.UnbyName(patternTable.getSelectionModel().getSelectedItem());
            for(Question q:questionList){
                if(question.getContent().equals(q.getContent())){
                    questionList.remove(q);
                    break;
                }
            }

            Pattern pattern = PatternDao.getPattern(PatternnameColumn.getCellData(patternTable.getSelectionModel().getSelectedItem()));
            cellData4.clear();
            cellData4.addAll(pattern.getQuestions());
            Patternquestiontable.setItems(null);
            Patternquestiontable.setItems(cellData4);

            //已解决，别忘了保存。。。
            /**__________________注意刷新函数Dao————————————————————————*/
            cellData5.clear();
            cellData5.addAll(questionList);
            addtoPatterntable.setItems(null);
            addtoPatterntable.setItems(cellData5);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "警告", "请选择你要添加的问题！");
    }


    @FXML
    private ListView<String> buildingList;
    @FXML
    private ListView<String> floorList;
    @FXML
    private ListView<String> roomList;
    @FXML
    private ListView<String> bedList;
    @FXML
    private RadioButton isUncommon;
    @FXML
    private Button getbedButton;
    @FXML
    private Button reducebedButton;
    @FXML
    private TextField getroomField;
    @FXML
    private TextField getbedField;
    @FXML
    private TextField getbuildingField;
    @FXML
    private TextField getfloorField;
    /**——————————————————————————————————————————楼宇管理——————————————————————————————*/
    @FXML
    void buildingButton(ActionEvent event) throws IOException {
        buildingPane.setVisible(true);
        questionPane.setVisible(false);
        patientpane.setVisible(false);
        bedPane.setVisible(false);
        patternPane.setVisible(false);

        reducebedButton.setVisible(false);
        getbedButton.setVisible(false);
        getbedField.setVisible(false);
        isUncommon.setVisible(false);

        ObservableList<String> strList = FXCollections.observableArrayList(StaffDao.getRoomBuildings());
        buildingList.setItems(null);
        buildingList.setItems(strList);

    }
    @FXML
    void choosebuilding(MouseEvent event) throws IOException {
        String buildingname = buildingList.getSelectionModel().getSelectedItem();
        List<Room> rooms = StaffDao.searchRooms(buildingname, null, null);
        List<String> roombuilding = new ArrayList<>();
        for (Room room : rooms) {
            String str = room.getFloorlocation();
            if(!roombuilding.contains(str)) roombuilding.add(str);
        }
        ObservableList<String> strList1 = FXCollections.observableArrayList(roombuilding);
        floorList.setItems(null);
        floorList.setItems(strList1);
        reducebedButton.setVisible(false);
        getbedButton.setVisible(false);
        getbedField.setVisible(false);
        isUncommon.setVisible(false);
        bedList.setItems(null);
        roomList.setItems(null);

    }
    @FXML
    void choosefloor(MouseEvent event) throws IOException {
        String floorname = floorList.getSelectionModel().getSelectedItem();
        List<Room> rooms = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorname,null);
        List<String> roomfloor = new ArrayList<>();
        for(Room room:rooms){
            String str = room.getName();
            if(!roomfloor.contains(str)) roomfloor.add(str);
        }

        ObservableList<String> strList = FXCollections.observableArrayList(roomfloor);
        roomList.setItems(strList);
        bedList.setItems(null);
        reducebedButton.setVisible(false);
        getbedButton.setVisible(false);
        getbedField.setVisible(false);
        isUncommon.setVisible(true);

    }
    @FXML
    void chooseroom(MouseEvent event) throws IOException {
        String roomname = roomList.getSelectionModel().getSelectedItem();
        List<Room> rooms = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorList.getSelectionModel().getSelectedItem(),roomname);
        isUncommon.setVisible(true);
        boolean j = !rooms.get(0).isCommon();
        isUncommon.setSelected(j);
        if(j){
            reducebedButton.setVisible(false);
            getbedButton.setVisible(false);
            getbedField.setVisible(false);
        }
        else{
            reducebedButton.setVisible(true);
            getbedButton.setVisible(true);
            getbedField.setVisible(true);
        }

        ObservableList<String> strList = FXCollections.observableArrayList(rooms.get(0).getBeds());
        bedList.setItems(null);
        bedList.setItems(strList);
    }
    @FXML
    void isUncommon(ActionEvent event) throws IOException {
        String roomname = roomList.getSelectionModel().getSelectedItem();
        List<Room> rooms = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorList.getSelectionModel().getSelectedItem(),roomname);
        if(rooms!=null){
            Room r2 = rooms.get(0);
            Room r1 = new Room(r2.getBuildinglocation(),r2.getFloorlocation(),r2.getName(),r2.isCommon(),r2.getBeds(),r2.getFull());
            boolean j = !r2.isCommon();
            r2.setCommon(j);
            StaffDao.changeRoom(r1,r2);
            if(j){
                reducebedButton.setVisible(true);
                getbedButton.setVisible(true);
                getbedField.setVisible(true);

            }
            else{
                reducebedButton.setVisible(false);
                getbedButton.setVisible(false);
                getbedField.setVisible(false);
            }
        }
    }
    @FXML
    void choosebed(MouseEvent event) {
//        String roomname = roomList.getSelectionModel().getSelectedItem();
//        List<Room> rooms = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorList.getSelectionModel().getSelectedItem(),roomname);
        isUncommon.setManaged(false);
        getbedButton.setManaged(true);
        reducebedButton.setManaged(true);
        getbedField.setManaged(true);
    }

    @FXML
    void reducebedButton(ActionEvent event) throws IOException {
        List<Room> rooms = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorList.getSelectionModel().getSelectedItem(),roomList.getSelectionModel().getSelectedItem());
        Room r2 = rooms.get(0);
            Room r1 = new Room(r2.getBuildinglocation(),r2.getFloorlocation(),r2.getName(),r2.isCommon(),r2.getBeds(),r2.getFull());
            List<String> beds = r2.getBeds();
            for(String str:beds){
                if(str.equals(bedList.getSelectionModel().getSelectedItem())){
                    beds.remove(str);
                    break;
                }
            }
            r2.setBeds(beds);
            StaffDao.changeRoom(r1,r2);

            String roomname = roomList.getSelectionModel().getSelectedItem();
            List<Room> roomsd = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorList.getSelectionModel().getSelectedItem(),roomname);
            ObservableList<String> strList = FXCollections.observableArrayList(roomsd.get(0).getBeds());
            bedList.setItems(null);
            bedList.setItems(strList);
    }
    @FXML
    void reduceroomButton(ActionEvent event) throws IOException {
        List<Room> list = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorList.getSelectionModel().getSelectedItem(),null);
        List<String> roomfloor = new ArrayList<>();
        if(list.size()>1){
            for(Room room:list){
                roomfloor.add(room.getName());
            }
            List<Room> rooms = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorList.getSelectionModel().getSelectedItem(),roomList.getSelectionModel().getSelectedItem());
            StaffDao.deleteRoom(rooms.get(0));

            String floorname = floorList.getSelectionModel().getSelectedItem();
            List<Room> roomsd = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),floorname,null);
            List<String> roomfloord = new ArrayList<>();
            for(Room room:roomsd){
                String str = room.getName();
                if(!roomfloord.contains(str)) roomfloord.add(str);
            }

            ObservableList<String> strList = FXCollections.observableArrayList(roomfloord);
            roomList.setItems(null);
            roomList.setItems(strList);
            bedList.setItems(null);
        }
        else if(list.size()<=1){
            SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "错误", "请删除上一级单位");
        }

    }
    @FXML
    void reducefloorButton(ActionEvent event) throws IOException {
        String buildingname = buildingList.getSelectionModel().getSelectedItem();

        List<Room> rooms = StaffDao.searchRooms(buildingname,floorList.getSelectionModel().getSelectedItem(),null);
        StaffDao.deleteRooms(rooms);
        List<Room> list = StaffDao.searchRooms(buildingname,null,null);
        List<String> roombuilding = new ArrayList<>();
        for(Room room:list){
            roombuilding.add(room.getFloorlocation());
        }
        ObservableList<String> strList = FXCollections.observableArrayList(roombuilding);
        floorList.setItems(null);
        floorList.setItems(strList);
        roomList.setItems(null);
        bedList.setItems(null);
    }
    @FXML
    void reducebuildingButton(ActionEvent event) throws IOException {
        List<Room> rooms = StaffDao.searchRooms(buildingList.getSelectionModel().getSelectedItem(),null,null);
        StaffDao.deleteRooms(rooms);
        ObservableList<String> strList = FXCollections.observableArrayList(StaffDao.getRoomBuildings());
        buildingList.setItems(null);
        buildingList.setItems(strList);
        floorList.setItems(null);
        roomList.setItems(null);
        bedList.setItems(null);
    }

    @FXML
    void getbedButton(ActionEvent event) throws IOException {
        String building = buildingList.getSelectionModel().getSelectedItem();
        String floor = floorList.getSelectionModel().getSelectedItem();
        String name = roomList.getSelectionModel().getSelectedItem();
        List<Room> list = StaffDao.searchRooms(building,floor,name);
        Room room = list.get(0);
        Room r2 = new Room(building,floor,name,room.isCommon(),room.getBeds(),room.getFull());
        List<String> bedlist = room.getBeds();
        String bedname = getbedField.getText();
        boolean j = true;
        for(String bed:bedlist){
            if(bed.equals(bedname)){
                j = false;
                break;
            }
        }

        if(j){
            bedlist.add(bedname);
            room.setBeds(bedlist);
            StaffDao.changeRoom(r2,room);

            ObservableList<String> strList = FXCollections.observableArrayList(room.getBeds());
            bedList.setItems(null);
            bedList.setItems(strList);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "该房间已存在");
        getbedField.clear();
    }
    @FXML
    void getroomButton(ActionEvent event) throws IOException {
        String floorname = floorList.getSelectionModel().getSelectedItem();
        String buildingname = buildingList.getSelectionModel().getSelectedItem();
        String name = getroomField.getText();
        List<Room> rooms = StaffDao.searchRooms(buildingname,floorname,null);
        List<String> bed = new ArrayList<>();
        List<Boolean> b = new ArrayList<>();
        bed.add("一号床");
        b.add(false);

        Room room = new Room(buildingname,floorname,name,true,bed,b);

        boolean j = true;
        for(Room r:rooms){
            if(r.getName().equals(room.getName())){
                SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "注意", "该房间已存在！");
                j = false;
                break;
            }
        }
        if(j){
            rooms.add(room);
            StaffDao.addRoom(room);
            List<String> roomfloor = new ArrayList<>();
            for(Room r:rooms){
                roomfloor.add(r.getName());
            }
            ObservableList<String> strList = FXCollections.observableArrayList(roomfloor);
            roomList.setItems(null);
            roomList.setItems(strList);
        }
        getroomField.clear();
    }
    @FXML
    void getfloorButton(ActionEvent event) throws IOException {
        String buildingname = buildingList.getSelectionModel().getSelectedItem();
        String name = getfloorField.getText();
        List<Room> list = StaffDao.searchRooms(buildingname,null,null);
        List<String> roombuilding = new ArrayList<>();
        boolean j = true;
        for(Room room:list){
            roombuilding.add(room.getFloorlocation());
            if(room.getFloorlocation().equals(name)){
                j = false;
                break;
            }
        }
        if(j){
            List<String> bed = new ArrayList<>();
            List<Boolean> b = new ArrayList<>();
            bed.add("一号床");
            b.add(false);
            Room room = new Room(buildingname,name,"A101",true,bed,b);
            StaffDao.addRoom(room);

            roombuilding.add(room.getFloorlocation());
            ObservableList<String> strList = FXCollections.observableArrayList(roombuilding);
            floorList.setItems(null);
            floorList.setItems(strList);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "该楼层已存在");
        getfloorField.clear();
    }
    @FXML
    void getbuildingButton(ActionEvent event) throws IOException {
        String name = getbuildingField.getText();
        List<Room> list = StaffDao.getRooms();
        boolean j = true;
        for(Room room:list){
            if(room.getBuildinglocation().equals(name)){
                j = false;
                break;
            }
        }
        if(j){
            List<String> bed = new ArrayList<>();
            List<Boolean> b = new ArrayList<>();
            bed.add("一号床");
            b.add(false);
            Room room = new Room(name,"一层","A101",true,bed,b);
            StaffDao.addRoom(room);

            ObservableList<String> strList = FXCollections.observableArrayList(StaffDao.getRoomBuildings());
            buildingList.setItems(null);
            buildingList.setItems(strList);
        }
        else SimpleTools.informationDialog(Alert.AlertType.WARNING, "提示", "抱歉", "该楼号已存在");
        getbuildingField.clear();
    }


    //注销
    @FXML
    void goback(ActionEvent event) throws Exception {
        ((Stage)goback.getScene().getWindow()).close();

        (new LogFrameController()).showWindow();
    }
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        officer = StaffDao.getInstance().getOfficer();
        nameLabel.setText("亲爱的"+officer.getName()+"，欢迎回家");

        usernametable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
        userbirthtable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getBirth()));
        usersextable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getSex()));
        useragetable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getAge()));
        userphonetable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getPhone()));
        userconnecttable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getContact()));
        userurcalltable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getUrgently()));
        userbedtable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getRoom()));
        userassesstable.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getAssessment()));

        usernametable.setCellFactory(TextFieldTableCell.forTableColumn());
        userbirthtable.setCellFactory(TextFieldTableCell.forTableColumn());
        usersextable.setCellFactory(TextFieldTableCell.forTableColumn());
        useragetable.setCellFactory(TextFieldTableCell.forTableColumn());
        userphonetable.setCellFactory(TextFieldTableCell.forTableColumn());
        userconnecttable.setCellFactory(TextFieldTableCell.forTableColumn());
        userurcalltable.setCellFactory(TextFieldTableCell.forTableColumn());
        userbedtable.setCellFactory(TextFieldTableCell.forTableColumn());
        userassesstable.setCellFactory(TextFieldTableCell.forTableColumn());

        usernametable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setName(t.getNewValue());
                });
        userbirthtable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setBirth(t.getNewValue());
                });
        usersextable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setSex(t.getNewValue());
                });
        useragetable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setAge(t.getNewValue());
                });
        userphonetable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setPhone(t.getNewValue());
                });
        userconnecttable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setContact(t.getNewValue());
                });
        userurcalltable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setUrgently(t.getNewValue());
                });
        userbedtable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setRoom(t.getNewValue());
                });
        userassesstable.setOnEditCommit(
                (TableColumn.CellEditEvent<Patient, String> t) -> {
                    ((Patient) t.getTableView().getItems().get(
                            t.getTablePosition().getRow())
                    ).setAssessment(t.getNewValue());
                });


        numColumn.setCellValueFactory(cellData2 -> new SimpleStringProperty(String.valueOf(cellData2.getValue().getNum())));
        typeColumn.setCellValueFactory(cellData2 -> new SimpleObjectProperty(cellData2.getValue().getType()));
        questionColumn.setCellValueFactory(cellData2 -> new SimpleObjectProperty(cellData2.getValue().getContent()));


        PatternnameColumn.setCellValueFactory(cellData3 -> new SimpleObjectProperty(cellData3.getValue().getName()));
        PatterntypeColumn.setCellValueFactory(cellData3 -> new SimpleObjectProperty(cellData3.getValue().getType()));

    }

    @Override
    public void start(Stage primaryStage) throws Exception{
        this.primaryStage = primaryStage;

        Parent root = FXMLLoader.load(getClass().getResource("../View/StaffController.fxml"));
        primaryStage.setTitle("NEU颐养中心");
        primaryStage.setScene(new Scene(root, 1200, 720));
        primaryStage.getIcons().add(new Image("file:src/resource/flour.png"));
        primaryStage.show();
    }
    public void  showWindow() throws Exception {
        start(primaryStage);
    }
    public static void main(String[] args) {
        launch(args);
    }
}
